package com.example.jdbcdemo.service.Impl;

import com.example.jdbcdemo.mapper.TokenMapper;
import com.example.jdbcdemo.pojo.Token;
import com.example.jdbcdemo.pojo.User;
import com.example.jdbcdemo.service.TokenInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Service
public class TokenImpl implements TokenInterface {

    @Autowired
    TokenMapper tokenMapper;

    /**
     * 添加token并返回token字符串
     * @param user
     * @return
     */
    //生成token
    @Override
    public String tokenInSign(User user) {
       Date date = new Date();
       Random r = new Random(date.getTime());
       long temp=0;
       for(int i=0;i<10;i++)
       {
           temp+=r.nextLong();
       }
       String str= ""+user.getName()+"#"+temp;
       tokenMapper.addToken(new Token(0, user.getUserType(), str,date));
       return str;
    }

    //验证token
    @Override
    public boolean verifyToken(String token) {
        Token t=tokenMapper.queryBytoken(token);
        //验证是否存在以及是否在有效期内
        if (t==null){
            return false;
        }
        else {
            return true;
        }
    }
}
